package com.cuiweiyou.bluemesh.ui;

import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;

import com.cuiweiyou.bluemesh.R;
import com.cuiweiyou.bluemesh.base.IPermissionActivity;
import com.cuiweiyou.bluemesh.bluetooth.BluetoothMaster;
import com.cuiweiyou.bluemesh.util.SPDataUtil;

import butterknife.ButterKnife;

public class FlashActivity extends IPermissionActivity {
    final int CODE_REQUEST_BLUETOOTH = 9099;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);
        ButterKnife.bind(this);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_REQUEST_BLUETOOTH) {
            if (BluetoothMaster.getInstance().isBluetoothEnable()) {
                runMainActivity();
            } else {
                exitApp(1);
            }
        }
    }

    @Override
    public void initView() {

        if (!BluetoothMaster.getInstance().isDeviceEnable()) {
            exitApp(0);
        } else {
            if (!BluetoothMaster.getInstance().isBluetoothEnable()) {
                Intent enableBluetoothIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBluetoothIntent, CODE_REQUEST_BLUETOOTH);
            } else {
                runMainActivity();
            }
        }
    }

    /**
     * start Ble scan，扫描按钮的处理函数
     */
    public void runMainActivity() {
        Intent intent;
        boolean firstTimeRunApp = SPDataUtil.getInstance().isFirstTimeRunApp();
        if (firstTimeRunApp) {
            intent = new Intent(this, BlueInitActivity.class);
        } else {
            intent = new Intent(this, MainActivity.class);

        }
        startActivity(intent);
        finish();
    }

    /**
     * @param i 0-手机不支持，1-用户不授权
     */
    private void exitApp(int i) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("退出");
        builder.setMessage("无法使用蓝牙功能");

        // 确定按钮
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
